import axios from 'axios';
import { getToken } from '@/utils/auth';
export const bdfFileFunc = () => {
  // type=1 列表下载 2-详情下载
  function downloadFileWithAxios(meshModelId, loading, type) {
    let VITE_APP_BASE_API = '/dev-api';
    if (import.meta.env.MODE === 'production') {
      VITE_APP_BASE_API = '/prod-api';
    }
    if (import.meta.env.MODE === 'green') {
      VITE_APP_BASE_API = '/isfd-api';
    }
    loading.value = true;
    axios.get(`${VITE_APP_BASE_API}/isfd/mesh/file/download?_id=${meshModelId}`, {
      responseType: 'blob',
      headers: { 'Authorization': 'Bearer ' + getToken() }
    })
    .then((response ) => {
      handleResponse(response);
    }).catch(() => {
      type == 1 ? loading.close() : loading.value = false;
    }).finally(() => {
      type == 1 ? loading.close() : loading.value = false;
    })
  }
  const handleResponse = (response) => {
    const contentType = response.headers['content-type'];
    const contentDisposition = response.headers['content-disposition'];
    
    let filename = 'downloaded_file'; // 默认文件名
  
    // 从 Content-Disposition 中提取文件名
    if (contentDisposition && contentDisposition.includes('filename=')) {
      filename = contentDisposition
        .split('filename=')[1]
        .split(';')[0]
        .replace(/['"]/g, ''); // 去除引号
    }
  
    console.log(`文件类型: ${contentType}`);
    console.log(`文件名: ${decodeURIComponent(filename)}`);
  
    // 处理文件内容
    const blob = new Blob([response.data], { type: contentType });
    saveFile(blob, decodeURIComponent(filename));
  }
  
  const batchDownloadBdfFile = (idList, zipName, loading) => {
    let VITE_APP_BASE_API = '/dev-api';
    if (import.meta.env.MODE === 'production') {
      VITE_APP_BASE_API = '/prod-api';
    }
    if (import.meta.env.MODE === 'green') {
      VITE_APP_BASE_API = '/isfd-api';
    }
    loading.value = true;
    axios.post(`${VITE_APP_BASE_API}/isfd/mesh/file/batch/downloadWithName`, {
      ids: idList,
      zipName
    }, {
      responseType: 'blob',
      headers: { 'Authorization': 'Bearer ' + getToken() }
    })
    .then((response ) => {
      handleResponse(response);
    }).catch(() => {
      loading.close();
    }).finally(() => {
      loading.close();
    })
  }
  
  function saveFile(blob, filename) {
    // 创建一个临时链接
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename; // 设置下载的文件名
    document.body.appendChild(a);
    a.click(); // 触发下载
  
    // 清理临时链接
    URL.revokeObjectURL(url);
    document.body.removeChild(a);
  }
  return {
    downloadFileWithAxios,
    batchDownloadBdfFile
  }
}